package com.leyou.auth.interceptors;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 虎哥
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取用户cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        if(StringUtils.isBlank(jwt)){
            // jwt为空，未登录
            throw new LyException(401, "未登录！");
        }
        // 2.验证jwt，获取用户信息
        Payload payload = jwtUtils.parseJwt(jwt);
        UserDetails user = payload.getUserDetail();
        // 3.判断结果，如果正确则放行
        if (user == null) {
            throw new LyException(401, "未登录！");
        }
        // 4.保存用户信息
        UserContext.setUser(user);
        UserContext.setJwt(jwt);
        // 放行
        log.info("用户{}正在访问。", user.getUsername());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        UserContext.removeUser();
    }
}
